package com.vn.gofriends.activity;

/**
 * Created by jacobTran-7437 on 2/24/2015.
 */
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.vn.gofriends.R;
import com.vn.gofriends.fragment.DiscoverFragment;
import com.vn.gofriends.fragment.MyTripFragment;
import com.vn.gofriends.item.NavDrawerItem;

public class Welcome extends FragmentActivity {

	public static String TAG = "Welcome";
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] mDrawerItem;
	private ArrayList<NavDrawerItem> itemModel;
	private TypedArray itemImages;
	private DrawerAdapter drawerAdapter;
	private int lastIndex = 1;
	ImageView pro;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		mTitle = mDrawerTitle = getTitle();
		mDrawerItem = getResources().getStringArray(R.array.nav_drawer_items);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		itemModel = new ArrayList<NavDrawerItem>();
		itemImages = getResources().obtainTypedArray(R.array.nav_drawer_icons);

		View header = getLayoutInflater().inflate(R.layout.header, null);
		pro = (ImageView) header.findViewById(R.id.profile_image);
		TextView txtUserName = (TextView) header.findViewById(R.id.txtUserName);
		Button btnLogOut = (Button) header.findViewById(R.id.btnLogout);
		TextView txtEmail = (TextView) header.findViewById(R.id.txtEmail);
		txtUserName.setText(ParseUser.getCurrentUser().getUsername());
		txtEmail.setText(ParseUser.getCurrentUser().getEmail());
		//
		// Locate the column named "ImageName" and set
		// the string
		ParseFile images = (ParseFile) ParseUser.getCurrentUser().get("avartar");
		if (images != null) {
			images.getDataInBackground(new GetDataCallback() {

				@Override
				public void done(byte[] data, ParseException e) {
					if (e == null) {
						Log.d("Vien", "We've got data in data.");
						// Decode the Byte[] into
						// Bitmap
						Bitmap bmp = BitmapFactory.decodeByteArray(data, 0,
								data.length);
						pro.setImageBitmap(bmp);
					} else {
						Log.d("Vien", e.getMessage());
					}
				}
			});
		}else{
			Log.d("Vien", "We've got data in data.");
		}
		
		btnLogOut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ParseUser.getCurrentUser().logOut();
				startActivity(new Intent(Welcome.this, MainActivity.class));
				finish();
			}
		});
		pro.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "Clicked",
						Toast.LENGTH_SHORT).show();
			}
		});

		mDrawerList.addHeaderView(header);
		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		getActionBar().setIcon(R.drawable.ic_launcher);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		for (int i = 0; i < mDrawerItem.length; i++) {
			itemModel.add(new NavDrawerItem(mDrawerItem[i], itemImages
					.getResourceId(i, -1)));
		}

		itemImages.recycle();
		drawerAdapter = new DrawerAdapter(itemModel);
		mDrawerList.setAdapter(drawerAdapter);
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		if (savedInstanceState == null) {
			selectItem(1);
			lastIndex = 1;
		}

	}

	public class DrawerItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			// TODO Auto-generated method stub

			if (position != 0) {
				lastIndex = position;
				selectItem(position);
			} else {
				mDrawerList.setItemChecked(lastIndex, true);
			}
		}

	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == MyTripFragment.REQUEST_CODE){
			 for (Fragment fragment : getSupportFragmentManager().getFragments()) {
		            fragment.onActivityResult(requestCode, resultCode, data);
		        }
			 if(resultCode == Activity.RESULT_OK){
				FragmentManager fragmentManager = getSupportFragmentManager();
		            List<Fragment> fragments = fragmentManager.getFragments();
		            for(android.support.v4.app.Fragment fragment : fragments){
		                if(fragment != null && fragment.getUserVisibleHint()) {
		                    if(fragment instanceof MyTripFragment)
		                        ((MyTripFragment) fragment).updateTrip();
		                }
		            }
			 }
		}
	}

	@SuppressLint("NewApi")
	private void selectItem(int position) {
		Fragment fragment = null;
		switch (position) {
		case 1:
			fragment = new DiscoverFragment();
			Log.d(TAG, "Position: " + position);
			break;
		case 2:
			fragment = new MyTripFragment();
			Log.d(TAG, "Position: " + position);
			break;
		case 3:
			Log.d(TAG, "Position: " + position);
			break;
		case 4:
			Log.d(TAG, "Position: " + position);
			break;
		case 5:
			Log.d(TAG, "Position: " + position);
			break;
		case 6:
			Log.d(TAG, "Position: " + position);
			break;
		case 7:
			Log.d(TAG, "Position: " + position);
			break;
		case 8:
			Log.d(TAG, "Position: " + position);
			break;
		default:
			break;
		}
		if (fragment != null) {
			Bundle bundle = new Bundle();
			bundle.putInt("Position", position - 1);
			fragment.setArguments(bundle);
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();
			mDrawerList.setItemChecked(position, true);
			setTitle(mDrawerItem[position - 1]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			Log.d(TAG, "error in craeting fragment");
		}
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// MenuInflater inflater = getMenuInflater();
	// inflater.inflate(R.menu.main, menu);
	//
	// SearchManager manager = (SearchManager)
	// getSystemService(Context.SEARCH_SERVICE);
	//
	// SearchView search = (SearchView) menu.findItem(R.id.action_websearch)
	// .getActionView();
	// search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
	// search.setOnQueryTextListener(new OnQueryTextListener() {
	// @Override
	// public boolean onQueryTextChange(String query) {
	// return true;
	//
	// }
	//
	// @Override
	// public boolean onQueryTextSubmit(String query) {
	// // TODO Auto-generated method stub
	// if (query.trim().length() != 0) {
	// Toast.makeText(getApplicationContext(),
	// "Searching for " + query.toString(),
	// Toast.LENGTH_SHORT).show();
	// }
	// return false;
	// }
	// });
	// return super.onCreateOptionsMenu(menu);
	// }

	// @Override
	// public boolean onPrepareOptionsMenu(Menu menu) {
	// // If the nav drawer is open, hide action items related to the content
	// // view
	// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
	// menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
	// return super.onPrepareOptionsMenu(menu);
	// }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		/*
		 * switch(item.getItemId()) { case R.id.action_websearch: // create
		 * intent to perform web search for this planet
		 * 
		 * return true; default: return super.onOptionsItemSelected(item); }
		 */
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@SuppressLint("NewApi")
	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private class DrawerAdapter extends BaseAdapter {

		ArrayList<NavDrawerItem> itemsmodel;

		public DrawerAdapter(ArrayList<NavDrawerItem> itemModel) {
			// TODO Auto-generated constructor stub
			this.itemsmodel = itemModel;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return itemsmodel.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return itemsmodel.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			// TODO Auto-generated method stub

			if (view == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				view = mInflater.inflate(R.layout.list_adapter, null);
			}
			ImageView img = (ImageView) view.findViewById(R.id.img);
			TextView name = (TextView) view.findViewById(R.id.name);
			name.setText(itemsmodel.get(position).getTitle());
			img.setImageResource(itemsmodel.get(position).getIcon());
			return view;
		}

	}

}